package cn.gson.querydsl.config;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.UnknownUnwrapTypeException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * <p>****************************************************************************</p>
 * <ul style="margin:15px;">
 * <li>Description : querydsl-solon-plugin</li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2024年07月19日</li>
 * <li>@author     : ____′↘夏悸</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
@Slf4j
public class SolonDatasourceConnectionProviderImpl extends DatasourceConnectionProviderImpl {

    private DataSource dataSource;

    public SolonDatasourceConnectionProviderImpl() {
        log.debug("init SolonDatasourceConnectionProviderImpl");
    }

    @Override
    @SuppressWarnings({"unchecked"})
    public <T> T unwrap(Class<T> unwrapType) {
        if (ConnectionProvider.class.equals(unwrapType) ||
            DatasourceConnectionProviderImpl.class.isAssignableFrom(unwrapType)) {
            return (T) this;
        } else if (DataSource.class.isAssignableFrom(unwrapType)) {
            return (T) dataSource;
        } else {
            throw new UnknownUnwrapTypeException(unwrapType);
        }
    }

    @Override
    public void configure(Map<String, Object> configValues) {
        dataSource = (DataSource) configValues.get(AvailableSettings.JAKARTA_JTA_DATASOURCE);
    }

    @Override
    public void stop() {
        dataSource = null;
    }

    @Override
    public Connection getConnection() throws SQLException {
        Connection connection = dataSource.getConnection();
        log.debug("获取jdbc连接：{}", connection);
        return connection;
    }

    @Override
    public void closeConnection(Connection connection) throws SQLException {
        log.debug("关闭jdbc连接：{}", connection);
        connection.close();
    }

    public boolean supportsAggressiveRelease() {
        return false;
    }

}
